package com.manage;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.manage.adapter.PendingAccountedOrderAdapter;
import com.manage.base.BaseActivity;
import com.manage.http.AsyncHttpPost;
import com.manage.http.DefaultThreadPool;
import com.manage.http.RequestException;
import com.manage.http.RequestParameter;
import com.manage.http.RequestResultCallback;
import com.manage.model.Order;
import com.manage.model.OrderItem;
import com.manage.sharedpreferences.SPConfig;
import com.manage.util.RequestUtils;
import com.manage.util.StringUtil;
import com.manage.util.ToastUtils;
import com.manage.widgets.AccountedConfirmDialog;
import com.manage.widgets.CustomProgressDialog;
import com.manage.widgets.DialogActionListener;

/**
 * 待入帐订单列表
 * @author liyoro
 * @date 2012-6-6
 * 
 */
public class PendingAccountedOrdersActivity extends BaseActivity implements OnClickListener, OnScrollListener {

	private static String TAG = "PendingAccountedOrdersActivity";

	private PendingAccountedOrderAdapter accountedAdapter = null;

	public static PendingAccountedOrdersActivity self = null;

	private AccountedConfirmDialog confirmDialog = null;

	CustomProgressDialog accountedOrderDialog = null; //入账的dialog

	// 加载
	private View loadingLayout;
	private ProgressBar progressBar;
	private TextView errText;
	
	//分页
	private int lastItem = 0;
	private boolean isEndFlag = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		self = this;
		this.setContentView(R.layout.activity_manage_container);
		initDatas();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
//		initDatas();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		page = 1;
		initDatas();
	}
	
	@Override
	public String getLeftBtnName() {
		return "返回";
	}

	@Override
	public String getTitleName() {
		return "待入帐订单";
	}

	@Override
	public boolean showButton() {
		return true;
	}

	@Override
	public void initView() {
		orderListview = (ListView) findViewById(R.id.listview1);

		// 加载更多
		loadingLayout = ((LayoutInflater)PendingAccountedOrdersActivity
				  .this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
				  .inflate(R.layout.more_row, null, false);

		// 加载到listActivity的底部
		orderListview.addFooterView(loadingLayout);
		
		accountedAdapter = new PendingAccountedOrderAdapter(this);
		orderListview.setAdapter(accountedAdapter);
		orderListview.setOnScrollListener(this);
		
		loadingLayout.setOnClickListener(this);
		loadingLayout.setClickable(false);
		
		progressBar = (ProgressBar)loadingLayout.findViewById(R.id.progressbar);
		errText = (TextView)loadingLayout.findViewById(R.id.err_text);
	}

	public void showProgress() {
		progressBar.setVisibility(View.VISIBLE);
		errText.setText("正在加载数据...");
		
		if(orderListview.getFooterViewsCount() == 0) {
			Log.d(TAG, "listView.getFooterViewsCount() == 0");
			orderListview.addFooterView(loadingLayout);
		}
	}
	
	public void hideProgress() {
		errText.setText("正在加载数据...");
		
		if(orderListview.getFooterViewsCount() != 0) {
			orderListview.removeFooterView(loadingLayout);
		}
	}
	
	public void showAgainProgress() {
		loadingLayout.setClickable(true);
		loadingLayout.setVisibility(View.VISIBLE);
		orderListview.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.GONE);
		errText.setVisibility(View.VISIBLE);
		errText.setText("获取数据失败，点击重试！");
	}
	
	@Override
	public void initDatas() {
		orderList.clear(); 

		if(page == 1) {
			orderList.clear();
			accountedAdapter.setValue(null);
			accountedAdapter.setClear(true);
		} else {
			accountedAdapter.setClear(false);
		}
		
		String shopID = sp.getString(SPConfig.SHOPID, "");
		String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
		RequestUtils.getOrderData(shopID, token, "3", String.valueOf(page), handler, this.requestList);
	}

	public Handler handler = new Handler() {
		public void handleMessage(Message msg) { 
			switch(msg.what) {
			case SUCCESS:

				if(orderList.size() < 5) {
					hideProgress();
				}
				
				Bundle bundle = msg.getData();
				String res = bundle.getString("res");
				
				if(res != null && !res.equals("[{}]") && res.length() > 15) {
					JSONArray jsonTemp = StringUtil.getJson(res);

					try {
						for(int i=0; i<jsonTemp.length(); i++) {
							Order order = new Order();
							JSONObject temp = new JSONObject(jsonTemp.getString(i));
							JSONObject temp0 = new JSONObject(temp.getString("order"));
							
							order.setOrderID(temp0.getString("order_id"));
							order.setOrderTime(temp0.getString("order_time"));
							order.setDeliveryCosts(temp0.getString("delivery_costs"));
							order.setClientAddition(temp0.getString("remark"));
							
							JSONObject temp2 = new JSONObject(temp.getString("user"));
							order.setClientName(temp2.getString("appellation"));
							order.setPhoneNumber(temp2.getString("tel"));
							order.setClientAddress(temp2.getString("address"));
							order.setRemark(temp2.getString("remark"));

							JSONArray temp3 = new JSONArray(temp0.getString("dishes"));
							ArrayList<OrderItem> dishesList = new ArrayList();
							
							for(int j=0; j< temp3.length(); j++) {
								OrderItem dish = new OrderItem();
								
								JSONObject temp4 = new JSONObject(temp3.getString(j));
								dish.setCaipin_ID(temp4.getString("dishes_id"));
								dish.setCaipin_name(temp4.getString("name"));
								dish.setCaipin_count(temp4.getString("count"));
								dish.setCaipin_price(temp4.getString("price"));
								
								dishesList.add(dish);
							}
							order.setDishes(dishesList);
							
							orderList.add(order);
						}
						Log.i(TAG, ":" + orderList.size());
						accountedAdapter.setValue(orderList);
					}
					catch (JSONException e) {
						e.printStackTrace();
					} 
					catch (Exception e) {
						e.printStackTrace();
					}
				} else {
//					deliveryAdapter.setValue(null);
					
					isEndFlag = true;
					hideProgress();
					Toast.makeText(PendingAccountedOrdersActivity.this, "已经是最后一页", 
							Toast.LENGTH_SHORT).show();
				}
				break;
			case FAIL:
//				ToastUtils.show(PendingAccountedOrdersActivity.this, "获取数据失败，请稍侯重试！", true);
				showAgainProgress();
				break;
			case ACCOUNTRDER:
				Bundle bundle2 = msg.getData();
				//modifyOrder(bundle2.getString("orderid"));
				confirm(bundle2.getString("orderid"), bundle2.getString("totalprice"));
				break;
			case ACCOUNTRDERSUCCESS:
				accountedOrderDialog.dismiss();
				confirmDialog.dismiss();
				page = 1;
				initDatas();
				ToastUtils.show(PendingAccountedOrdersActivity.this, "入账成功！", true);
				break;
			case ACCOUNTRDERFAIL:
				accountedOrderDialog.dismiss();
				confirmDialog.dismiss();
				ToastUtils.show(PendingAccountedOrdersActivity.this, "入账失败，请稍侯重试！", true);
				break;
			}
		}
	};
	
	/**
	 * 入账-->4：已完成
	 * @param paramString1 orderid
	 * @param paramString2 订单实收总价
	 * @param paramString3 用户备注
	 * @param paramString3 1:待受理订单，2：待配送订单，3：待入账订单，4：已完成,5:已取消
	 */
	private void accountedOrder(String paramString1, String paramString2, String paramString3) {
		String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
		
		List<RequestParameter> parameterList = new ArrayList<RequestParameter>();
		parameterList.add(new RequestParameter("token", token));
		parameterList.add(new RequestParameter("orderid", paramString1));
		parameterList.add(new RequestParameter("status", "4"));
		parameterList.add(new RequestParameter("paidup", paramString2));
		parameterList.add(new RequestParameter("remard", paramString3));
		
		AsyncHttpPost httpost = new AsyncHttpPost(null, MODIFYORDERURL, parameterList,
				new RequestResultCallback(){

				@Override
				public void onSuccess(Object o) {
					Log.i("HttpPostExample", "HttpPostExample  request  onSuccess result :"+((String)o).toString());
						
					try {
						JSONObject jsonTemp = new JSONObject(((String)o).toString());
						boolean res = jsonTemp.getBoolean("status_return");
						Log.i(TAG, "res:"+res);
						
						if(res == true) {
							handler.sendEmptyMessage(ACCOUNTRDERSUCCESS);
						} 
						else{
							handler.sendEmptyMessage(ACCOUNTRDERFAIL);  
						} 
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
					
				@Override
				public void onFail(Exception e) {
					Log.i("HttpPostExample", "HttpPostExample  request   onFail :"+((RequestException)e).getMessage());
						
			        handler.sendEmptyMessage(ACCOUNTRDERFAIL);  //向Handler发送消息
				}
		});
		
		DefaultThreadPool.getInstance().execute(httpost);
	 
		this.requestList.add(httpost);
	}
	
	/**
	 * 确认入账dialog
	 * @param paramString orderid
	 * @param paramString2 totalprice
	 */
	private void confirm(final String orderid, String totalprice) {
		confirmDialog = new AccountedConfirmDialog(PendingAccountedOrdersActivity.this, totalprice);
		confirmDialog.show();
		confirmDialog.setDialogConfirmAction(new DialogActionListener() {
			
			@Override
			public void confirmAction(String paramString, String paramString2) {
				accountedOrderDialog = new CustomProgressDialog(PendingAccountedOrdersActivity.this, 
						"正在入账...", "正在入账，请稍候...");
				accountedOrderDialog.show();
				accountedOrder(orderid, paramString, paramString2);
			}
			
			@Override
			public void confirmAction() {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount-1;
//		Log.d(TAG, "lastItem:" + lastItem);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		if(true == isEndFlag){
			return;
		}
		showProgress();
		
		if (lastItem == accountedAdapter.getCount() 
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			page++;
//			Log.d(TAG, "nowpage:" + page);
			initDatas();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.more_self:
			initDatas();
			break;
		default:
			break;
		}
	}
}
